#include "web_server.h"
#include "utils_log.h"
#include "utils_file_ex.h"
#include "nlohmann/json.hpp"
#include "http_server_diagnosis.h"
namespace El {
namespace WebServer {

bool web_server_init(nlohmann::json &config)
{
    auto &server = IHttpServer::GetInstance();

    // 检查/home/web目录是否存在，如果存在则优先使用
    std::string web_dir = "/mnt/assets/web";
    std::string data_web_dir = "/home/web";

    if (Utils::IsDirectoryExists(data_web_dir)) {
        EL_INFO("Found web directory in data partition: {}, using it", data_web_dir);
        web_dir = data_web_dir;
    } else if (config.contains("web_dir")) {
        web_dir = config["web_dir"].get<std::string>();
    }
    server.SetMountPoint(web_dir);

    // 配置SSL证书
    std::string cert_file = "/app/ssl/server.crt";
    std::string key_file = "/app/ssl/server.key";
    if (config.contains("ssl")) {
        const auto &ssl = config["ssl"];
        cert_file = ssl.value("cert_file", cert_file);
        key_file = ssl.value("key_file", key_file);
    }
    server.SetSSLCert(cert_file, key_file);

    // 启动服务器
    if (!server.Start()) {
        EL_ERROR("Failed to start web server");
        return false;
    }

    // 启动诊断
    HttpServerDiagnosis::GetInstance().Start();

    return true;
}

} // namespace WebServer
} // namespace El